import Router from "koa-router";

import userMongoose from "@/model/user";

import orderMongoose from "@/model/order";

// import { GetMongoConnect, getObjectId } from "@/config/db";

import { PERFIX_URL } from "@/config/router";

const KoaRouter = new Router();

// let mongoClient = new GetMongoConnect();

KoaRouter.prefix(`${PERFIX_URL}/user`);

// 查询
KoaRouter.get("/find", async (ctx) => {
  const { _id } = ctx.query;
  // mongodb实现
  // const data = await mongoClient.find(
  //   "test",
  //   "users",
  //   _id ? { _id: getObjectId(_id) } : {}
  // );

  // mongoose实现
  const data = await userMongoose.find(_id ? { _id } : {});
  console.log(data, 2345678)

  ctx.status = 200;
  ctx.body = data;
});

// 增加
KoaRouter.post("/add", async (ctx) => {
  // mongodb实现
  // const data = await mongoClient.add("test", "users", ctx.request.body);

  // mongoose实现
  const data = await userMongoose.create(ctx.request?.body);

  ctx.status = 200;
  ctx.body = {
    data,
  };
});

// 删除
KoaRouter.delete("/delete", async (ctx) => {
  const { _id } = ctx.query;
  // mongodb实现
  // const data = await mongoClient.delete("test", "users", {
  //   _id: getObjectId(_id),
  // });

  // mongoose实现
  const data = await userMongoose.findByIdAndDelete({ _id });

  ctx.status = 200;
  ctx.body = { data };
});

// 修改
KoaRouter.patch("/update", async (ctx) => {
  const { _id } = ctx.query;
  // mongodb实现
  // const res = await mongoClient.update(
  //   "test",
  //   "users",
  //   { _id: getObjectId(_id) },
  //   JSON.parse(ctx.request.body)
  // );

  // mongoose实现
  const data = await userMongoose.findByIdAndUpdate(
    { _id },
    { $set: JSON.parse(ctx.request.body) }
  );

  ctx.status = 200;
  ctx.body = { data };
});

// 联表添加
KoaRouter.post("/savePopulate", async (ctx) => {
  console.log(ctx.request.body)
  const data = await orderMongoose.create({
    ...ctx.request.body,
    users: ctx.query._id,
  });
  ctx.body = {
    data,
  };
});

// 联表查询
KoaRouter.get("/findPopulate", async (ctx) => {
  const data = await orderMongoose
    .find({ users: { _id: ctx.query._id } }) // 通过关联表的_id来查询
    .populate("users", "_id"); // (可以不要这个)关联表的字段只返回_id
  ctx.body = {
    data,
  };
});

export default KoaRouter;
